package com.yzw.phonestoreservice.exception;

import com.yzw.phonecommen.common.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;


import static com.yzw.phonecommen.common.ResultCodeEnum.NULL_POINT;
import static com.yzw.phonecommen.common.ResultCodeEnum.UNKNOW_RESAON;

/**
 * @BelongsProject: springbootdome
 * @BelongsPackage: com.yu.sbmpsum1.exception
 * @Author: yanhongwei
 * @CreateTime: 2022-10-30  17:26
 * @Description: TODO 全局异常处理
 * @Version: 1.0
 */
@ControllerAdvice //通知异常
@ResponseBody
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 拦截业务异常，返回业务异常信息
     * @param ex
     * @return
     */
    @ExceptionHandler(BusinessErrorException.class) //自定义异常
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleBusinessError(BusinessErrorException ex) {
        Integer code = ex.getCode();
        String message = ex.getMessage();
        R r = R.ok();
        r.setCode(code);
        r.setMessage(message);
        return  r;
    }

    /**
     * 空指针异常
     * @param ex NullPointerException
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleTypeMismatchException(NullPointerException ex) {
        logger.error("空指针异常，{}", ex.getMessage());
        return R.setResult(NULL_POINT);
    }
    @ExceptionHandler(PhoneException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleBusinessError(Exception ex) {
        logger.error(ex.getMessage(),ex);
        return R.error().message(ex.getMessage());
    }

    /**
     * 系统异常 预期以外异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleUnexpectedServer(Exception ex) {
        logger.error("系统异常：", ex);
        return R.setResult(UNKNOW_RESAON);
    }

}